package com.ymdx.action;

import com.opensymphony.xwork2.ModelDriven;
import com.ymdx.entity.User;
import com.ymdx.entity.Verification;
import com.ymdx.service.UserService;
import com.ymdx.service.VerificationService;
import com.ymdx.util.Page;
import com.ymdx.util.sms.SMSUtil;
import com.ymdx.util.tool.BeanCopyUtil;
import com.ymdx.util.tool.DateUtils;
import com.ymdx.util.tool.Tools;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yangliwei on 2017/8/13.
 */
public class UserAction extends GenericActionSupport implements ModelDriven<User> {
    private User user;
    private String verificationCode;//验证码
    private Integer verificationType;//验证码类型
    private Page<User> page;
    private Integer pageSize=9;
    private Integer pageNo=1;
    private String oldPassword;//修改密码时使用
    private String ids;//用来批量删除

    @Resource
    private UserService userService;

    @Resource
    private VerificationService verificationService;


    private static final Integer EFFICTIVE = 3;//短信验证码的有效期 分钟


    /**
     * 注册
     *
     * @return
     */
    @Action(value = "/user/register", results = {@Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String register() {
//        sout
        String mobile = user.getMobile();
        String password = user.getPassword();
        String verification = verificationCode;
        if (StringUtils.isAnyBlank(mobile, password, verification)) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        //重复注册
        if (userService.getUserByMobile(mobile) != null) {
            responseTool.setStatus(0);
            responseTool.setCode("user_mobile_mutil");
            return SUCCESS;
        }

        if (!Tools.isMobile(mobile)) {
            responseTool.setStatus(0);
            responseTool.setCode("user_mobile_error");
            return SUCCESS;
        }
        checkOut(mobile, verification);
        if (responseTool.getStatus() == 0) {
            return SUCCESS;
        }
        //使用手机号加密码的md5加密
        password = DigestUtils.md5Hex(mobile+password);
        User user = new User();
        user.setCreateTime(new Date());
        user.setNickName(mobile);
        user.setMobile(mobile);
        user.setPassword(password);
        user.setHeader("");
        user.setGender("");
        user.setEmail("");
        user.setQq("");
        user.setWeixin("");
        user.setParentMobile("");
        user.setStudentId("");
        userService.save(user);
        responseTool.setStatus(1);
        responseTool.setData(user);
        return SUCCESS;
    }



    /**
     * 用户登陆
     * @return
     */
    @Action(value = "/user/login", results = {@Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String login() {
        String mobile = user.getMobile();
        String password = user.getPassword();
        if (StringUtils.isAnyBlank(mobile, password)) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        String result = String.valueOf(DigestUtils.md5Hex(mobile + password));
        User oldUser = userService.getUserByMobile(mobile);
        if (result.equalsIgnoreCase(oldUser.getPassword())) {
            session.put("user", oldUser.getId());
            responseTool.setStatus(1);
            responseTool.setData(oldUser);
            return SUCCESS;
        }
        responseTool.setStatus(0);
        responseTool.setCode("user_login_error");
        return SUCCESS;
    }

    /**
     *  并返回用户基本信息
     */
    @Action(value = "/user/detail",results = {@Result(type = JSON,name=SUCCESS,params ={
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id,data\\.mobile,data\\.nickName,data\\.header,data\\.gender,data\\.email,data\\.qq,data\\.weixin,data\\.parentMobile"
    } )})
    public String detail(){
        Object obj = session.get("user");
        if(obj == null){
            responseTool.setStatus(0);
            responseTool.setCode("user_no_login");
            return SUCCESS;
        }

        User oldUser = userService.getById(User.class,Long.parseLong(obj.toString()));
        if(oldUser == null){
            responseTool.setStatus(0);
            responseTool.setCode("user_not_exist");
            return SUCCESS;
        }
        responseTool.setStatus(1);
        responseTool.setData(oldUser);
        return SUCCESS;
    }


    /**
     * 用户信息编辑 主要保存用户修改的信息
     */
    @Action(value = "/user/edit",results = {@Result(type = JSON,name=SUCCESS,params ={
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    } )})
    public String edit(){
        Object obj = session.get("user");
        if(obj == null){
            responseTool.setStatus(0);
            responseTool.setCode("user_no_login");
            return SUCCESS;
        }
        String password = user.getPassword();

        User oldUser = userService.getById(User.class,Long.parseLong(obj.toString()));
        if(oldUser == null){
            responseTool.setStatus(0);
            responseTool.setCode("user_not_exist");
            return SUCCESS;
        }
        if(!(StringUtils.isAllBlank(password,oldPassword)||(StringUtils.isNotBlank(password)&&StringUtils.isNotBlank(oldPassword)))){
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        if(StringUtils.isNotBlank(oldPassword)){
            if(!DigestUtils.md5Hex(oldUser.getMobile()+oldPassword).equals(oldUser.getPassword())){
                responseTool.setStatus(0);
                responseTool.setCode("user_password_error");
                return SUCCESS;
            }
            user.setPassword(DigestUtils.md5Hex(oldUser.getMobile()+password));
        }
        BeanCopyUtil.copyProperties(user,oldUser,true);
        oldUser.setHeader(oldUser.getHeader().replace("\"",""));
        userService.save(oldUser);
        responseTool.setStatus(1);
        responseTool.setData(oldUser.getId());
        return SUCCESS;
    }

    /**
     * 用户信息分页
     */
    @Action(value = "/admin/user/page",results = {@Result(type = JSON,name=SUCCESS,params ={
            "root", "page",
            "includeProperties", "pageNo,pageSize,totalCount,result\\[\\d+\\]\\.id,result\\[\\d+\\]\\.mobile,result\\[\\d+\\]\\.nickName,result\\[\\d+\\]\\.gender,result\\[\\d+\\]\\.email,result\\[\\d+\\]\\.studentId"

    } )})
    public String page(){
        //妈个鸡 相信一波过滤器
        String nickName = user.getNickName();
        String mobile = user.getMobile();
        String studentId = user.getStudentId();
        Map<String,Object> args = new HashMap<>();
        if(StringUtils.isNotBlank(nickName)){
            args.put("nickName",nickName);
        }
        if(StringUtils.isNotBlank(mobile)){
            args.put("mobile",mobile);
        }
        if(StringUtils.isNotBlank(studentId)){
            args.put("studentId",studentId);
        }
        if(page == null){
            page = new Page<User>();
            page.setPageNo(pageNo);
            page.setPageSize(pageSize);
        }
        page = userService.page(page,args);
        responseTool.setStatus(1);
        responseTool.setData(page);
        return SUCCESS;
    }

    /**
     *  并返回用户基本信息
     */
    @Action(value = "/admin/user/detail",results = {@Result(type = JSON,name=SUCCESS,params ={
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id,data\\.mobile,data\\.nickName,data\\.header,data\\.gender,data\\.email,data\\.qq,data\\.weixin,data\\.parentMobile"
    } )})
    public String adminUserDetail(){
        Long id = user.getId();
        if(id== null){
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        User oldUser = userService.getById(User.class,id);
        if(oldUser == null){
            responseTool.setStatus(0);
            responseTool.setCode("user_not_exist");
            return SUCCESS;
        }
        responseTool.setStatus(1);
        responseTool.setData(oldUser);
        return SUCCESS;
    }

    /**
     * 用户信息管理
     * 用来编辑用户信息
     */
    @Action(value = "/admin/user/manager",results = {@Result(type = JSON,name=SUCCESS,params ={
            "root", "responseTool",
            "includeProperties", "status,code,message,data"
    } )})
    public String manager(){
        Object obj = session.get("admin");
        if(obj == null){
            responseTool.setStatus(0);
            responseTool.setCode("admin_no_login");
            return SUCCESS;
        }
        String mobile = user.getMobile();
        String password = user.getPassword();
        if(StringUtils.isNotBlank(mobile)){
            responseTool.setStatus(0);
            responseTool.setCode("parameter_error");
            return SUCCESS;
        }

        Long id = user.getId();
        if(id == null){
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        User oldUser = userService.getById(User.class,id);
        if(oldUser == null){
            responseTool.setStatus(0);
            responseTool.setCode("user_not_exist");
            return  SUCCESS;
        }
        if(StringUtils.isNotBlank(password)){
            user.setPassword(DigestUtils.md5Hex(oldUser.getMobile()+password));
        }
        BeanCopyUtil.copyProperties(user,oldUser,true);
        userService.save(oldUser);
        responseTool.setStatus(1);
        responseTool.setData(oldUser.getId());
        return SUCCESS;
    }

    @Action(value = "/admin/user/delete",results = {@Result(type = JSON,name=SUCCESS,params ={
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    } )})
    public String delete(){
        Object obj = session.get("admin");
        if(obj == null){
            responseTool.setStatus(0);
            responseTool.setCode("admin_no_login");
            return SUCCESS;
        }
        String mobile = user.getMobile();
        if(StringUtils.isNotBlank(mobile)){
            responseTool.setStatus(0);
            responseTool.setCode("parameter_error");
            return SUCCESS;
        }
        Long id = user.getId();
        User oldUser = userService.getById(User.class,id);
        if(oldUser == null){
            responseTool.setStatus(0);
            responseTool.setCode("user_not_exist");
            return  SUCCESS;
        }
        if(oldUser.getValid() == false){
            responseTool.setStatus(0);
            responseTool.setCode("user_not_exist");
            return SUCCESS;
        }
        oldUser.setValid(false);
        userService.save(oldUser);
        responseTool.setStatus(1);
        responseTool.setData(oldUser);
        return SUCCESS;
    }

    @Action(value = "/admin/user/batchDelete",results = {@Result(type = JSON,name=SUCCESS,params ={
            "root", "responseTool",
            "includeProperties", "status,code,message,data"
    } )})
    public String batchDelete(){

        return SUCCESS;
    }


    /**
     * 获取短信验证码
     *
     * @return
     */
    @Action(value = "/user/verification", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.verificationCode"
    })})
    public String verification() {
        String mobile = user.getMobile();
        if (StringUtils.isBlank(mobile)) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        //设置短信类型
        String type = SMSUtil.REGISTER_TEMPLATE_CODE;
        if (verificationType != null && verificationType == 2) {
            type = SMSUtil.REPASSWORD_TEMPLATE_CODE;
        }
        String code = String.valueOf(((int) ((Math.random() * 9 + 1) * 100000)));
        if (SMSUtil.sendMessage(mobile, code, type)) {
            Verification verification = verificationService.getByMobile(mobile);
            Verification save = verification == null ? new Verification() : verification;
            save.setMobile(mobile);
            save.setSendTime(new Date());
            save.setVerificationCode(code);
            save.setTimes(save.getTimes() == null ? 1 : save.getTimes() + 1);
            verificationService.save(save);
            responseTool.setStatus(1);
            responseTool.setData(save);
            return SUCCESS;
        }
        responseTool.setStatus(0);
        responseTool.setCode("user_verification_fail");
        return SUCCESS;
    }

    /**
     * 登出
     * @return
     */
    @Action(value = "/user/logout", results = {@Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message"
    })})
    public String logout() {
        session.remove("user");
        request.getSession().invalidate();
        responseTool.setStatus(1);
        return SUCCESS;
    }

    private void checkOut(String mobile, String code) {
        //数据库获取的对象
        Verification verification = verificationService.getByMobileCode(mobile, code);
        if (verification == null || verification.getSendTime() == null) {
            responseTool.setStatus(0);
            responseTool.setCode("user_verification_error");
            return;
        }
        Date sendTime = verification.getSendTime();
        Date now = new Date();
        if (sendTime == null || sendTime.before(DateUtils.getMinuteMove(now, -EFFICTIVE))) {
            responseTool.setStatus(0);
            responseTool.setCode("user_verification_valid");
            return;
        }
        responseTool.setStatus(1);

    }

    @Override
    public User getModel() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

    public String getVerificationCode() {
        return verificationCode;
    }

    public void setVerificationCode(String verificationCode) {
        this.verificationCode = verificationCode;
    }

    public Integer getVerificationType() {
        return verificationType;
    }

    public void setVerificationType(Integer verificationType) {
        this.verificationType = verificationType;
    }

    public Page<User> getPage() {
        return page;
    }

    public void setPage(Page<User> page) {
        this.page = page;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }

    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }
}
